package org.west.sky.scripture.ratelimiter;

import com.google.common.util.concurrent.RateLimiter;

import java.time.LocalTime;

/**
 * @author chz
 * @date 2022/3/21
 * @description: 令牌桶限流算法--谷歌实现
 */
public class TokenBucketRateLimiter {

    public static void main(String[] args) throws InterruptedException {
        //创建一个qps为2的令牌桶，即每500ms往桶里面丢一个令牌
        RateLimiter rateLimiter = RateLimiter.create(2);
        for (int i = 0; i < 10; i++) {
            if (rateLimiter.tryAcquire()) {
                System.out.println(LocalTime.now() + " " + (i + 1) + " 干点什么");
            } else {
                System.out.println(LocalTime.now() + " " + (i + 1) + " 被限流了");
            }
            Thread.sleep(250);
        }
    }
}
